<template>
  <view class="container">
    <cu-custom bgColor="bg-green" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">账单详情</block>
    </cu-custom>

    <view class="bg-top bg-green">
      <view class="top-box shadow">
        <view class="qh-title text-bold text-blue text-xl u-text-center">
          <input v-model="account.name" placeholder="请输入账单名称" name="input" />
        </view>

        <view class="cu-list menu">
          <!-- 账本选择 -->
          <!-- <view class="cu-item" style="padding: 0;">
						<view class="content">
							<text class="cuIcon-newshotfill text-mauve margin-right-xs"></text>
							<text class="text-black">账本</text>
						</view>
						<view class="action">
						</view>
					</view> -->
          <view class="cu-item" style="padding: 0">
            <scroll-view scroll-x class="bg-white" style="height: 165upx" scroll-y>
              <view class="cu-list grid col-5">
                <view class="justify-center" v-for="(item, index) in books" :key="index" @click="changeBookClass(item)">
                  <view
                    class="cu-avatar round lg margin-xs iconfont"
                    :class="item.iconName"
                    :style="item.value === account.accountBookId ? 'background-color: #1cbbb4' : ''"
                  ></view>
                  <view>{{ item.label }}</view>
                </view>
              </view>
            </scroll-view>
          </view>

          <!-- 旧版本 账本 -->
          <!-- <view class="cu-item" style="padding: 0;">
						<view class="content">
							<text class="cuIcon-newshotfill text-mauve margin-right-xs"></text>
							<text class="text-black">账本</text>
						</view>
						<view class="action">
							<view @tap="bookShow = true;" class="cu-tag round bg-mauve light">{{ account.bookName }}</view>
						</view>
					</view> -->

          <!-- 旧版本 账本选择器 -->
          <!-- <u-picker
						title="账本"
						mode="selector"
						v-model="bookShow"
						:range="books"
						range-key="label"
						@confirm="bookConfirm"
						:default-selector="selBook"
					></u-picker> -->

          <view class="cu-item" style="padding: 0">
            <view class="content">
              <text class="cuIcon-tagfill text-cyan margin-right-xs"></text>
              <text class="text-black">类别</text>
            </view>

            <view class="action">
              <u-subsection
                class="category-subsection"
                active-color="#1cbbb4"
                :list="categories"
                @change="changeCategory"
                :current="categoryIndex"
              ></u-subsection>
            </view>
          </view>

          <!-- 类型选择 -->
          <view class="cu-item" style="padding: 0">
            <scroll-view scroll-x class="bg-white" style="height: 315upx" scroll-y>
              <view class="cu-list grid col-5">
                <view class="justify-center" v-for="(item, index) in types" :key="index" @click="changeTypeClass(item)">
                  <!-- 支出 -->
                  <view
                    v-if="categoryIndex === 0"
                    class="cu-avatar round lg margin-xs iconfont"
                    :class="item.iconName"
                    :style="item.value === account.accountCategoryId ? 'background-color: #e03997' : ''"
                  ></view>
                  <!-- 收入 -->
                  <view
                    v-if="categoryIndex === 1"
                    class="cu-avatar round lg margin-xs iconfont"
                    :class="item.iconName"
                    :style="item.value === account.accountCategoryId ? 'background-color: #8dc63f' : ''"
                  ></view>
                  <view>{{ item.label }}</view>
                </view>
              </view>
            </scroll-view>
          </view>

          <!-- 旧版本 类型选择器 -->
          <!-- <view class="cu-item" style="padding: 0;">
						<view class="content">
							<text class="cuIcon-tagfill text-blue margin-right-xs"></text>
							<text class="text-black">类型</text>
						</view>
						<view class="action">
							<view @tap="typeShow = true;" class="cu-tag round bg-blue light">{{ account.typeName ? account.typeName : '请选择' }}</view>
						</view>
					</view> -->

          <!-- 旧版本 类型选择器 -->
          <!-- <u-picker
						title="类型"
						mode="selector"
						v-model="typeShow"
						:range="types"
						range-key="label"
						@confirm="typeConfirm"
						:default-selector="selType"
					></u-picker> -->

          <view class="cu-item" style="padding: 0">
            <view class="content">
              <text v-if="categoryIndex == 0" class="cuIcon-rechargefill text-red"></text>
              <text v-if="categoryIndex == 0" class="text-black">支出金额</text>

              <text v-if="categoryIndex == 1" class="cuIcon-rechargefill text-green"></text>
              <text v-if="categoryIndex == 1" class="text-black">收入金额</text>
            </view>
            <view class="action">
              <!-- <u-input class="text-sm u-font-28 input-width-220" :custom-style="{color: categoryIndex == 0 ? 'red' : 'green'}" v-model="account.amt" placeholder="请输入金额" type="digit"></u-input> -->

              <view v-if="categoryIndex == 0" @tap="keyBoardShow = true" class="cu-tag round bg-red light">
                {{ account.amt ? account.amt : '请点击输入金额' }}
              </view>
              <view v-if="categoryIndex == 1" @tap="keyBoardShow = true" class="cu-tag round bg-green light">
                {{ account.amt ? account.amt : '请点击输入金额' }}
              </view>
            </view>
          </view>

          <!-- 数字键盘 -->
          <u-keyboard
            mode="number"
            v-model="keyBoardShow"
            :mask="false"
            :tooltip="false"
            @change="valChange"
            @backspace="backspace"
          ></u-keyboard>

          <view class="cu-item" style="padding: 0">
            <view class="content">
              <text class="cuIcon-timefill text-orange margin-right-xs"></text>
              <text class="text-black">记录时间</text>
            </view>
            <view class="action">
              <view @tap="timeShow = true" class="cu-tag round bg-orange light">{{ account.createTime }}</view>
            </view>
          </view>

          <!-- 账单时间选择 -->
          <u-picker
            title="记录时间"
            mode="time"
            v-model="timeShow"
            :params="params"
            :default-time="account.createTime"
            end-year="2099"
            @confirm="timeConfirm"
          ></u-picker>

          <view class="cu-item" style="padding: 0">
            <view class="content">
              <text class="cuIcon-timefill text-pink margin-right-xs"></text>
              <text class="text-black">修改时间</text>
            </view>
            <view class="action">
              <view class="cu-tag round bg-pink light">{{ account.updateTime }}</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 保存按钮 -->
      <view class="padding-lr flex margin-top-sm" style="justify-content: space-between; width: 750rpx">
        <button class="saveRecord" :style="[inputStyle]" @tap="update" style="width: 100%">保存记录</button>
      </view>
    </view>

    <!-- 提示框 -->
    <Confirm ref="Confirm" :showClose="false"></Confirm>
  </view>
</template>

<script>
import Confirm from '@/components/confirm.vue'

export default {
  data() {
    return {
      account: {},
      categories: [
        {
          name: '支出',
          id: 1
        },
        {
          name: '收入',
          id: 2
        }
      ],
      categoryIndex: 0,
      books: [],
      selBook: [0],
      bookShow: false,
      types: [],
      selType: [0],
      typeShow: false,
      timeShow: false,
      params: {
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true,
        second: true,
        timestamp: true
      },
      keyBoardShow: false,
      confirmIndex: 0
    }
  },
  computed: {
    inputStyle() {
      let style = {}
      if (this.account.name && this.account.accountCategoryId && this.account.amt && this.confirmIndex == 0) {
        style.color = '#fff'
        style.backgroundColor = this.$u.color['success']
      }
      return style
    }
  },
  components: {
    Confirm
  },
  async onLoad(option) {
    this.getAccountBookList()
    this.getDetail(option.id)
  },
  methods: {
    async getDetail(id) {
      const res = await this.$u.api.getAccountDetail(id)
      this.account = res
      this.account.amt = String(this.account.amt)

      if (res.accountCategory == 1) {
        // 支出
        this.categoryIndex = 0
      } else {
        // 收入
        this.categoryIndex = 1
      }

      // 查询类别的全部类型
      await this.getTypeListByCategoryId(res.accountCategory)

      this.books.forEach((book, index) => {
        if (book.value == res.accountBookId) {
          this.selBook[0] = index
        }
      })

      this.types.forEach((type, index) => {
        if (type.value == res.accountCategoryId) {
          this.selType[0] = index
        }
      })
    },
    /**
     * 类别选择
     */
    changeCategory(index) {
      this.categoryIndex = index
      this.getTypeListByCategoryId(this.categories[index].id)
      // 清空类型
      this.account.accountCategoryId = null
      this.account.typeName = ''
    },
    /**
     * 获取所有的账本信息
     */
    async getAccountBookList() {
      const res = await this.$u.api.getAccountBookList()
      let data = JSON.parse(JSON.stringify(res))

      this.books = []
      data.forEach((item) => {
        let dat = {
          label: item.name,
          value: item.id,
          iconName: item.iconName
        }

        this.books.push(dat)
      })
    },
    /**
     * 根据类别查询类型信息
     * @param {Object} categoryId
     */
    async getTypeListByCategoryId(categoryId) {
      const res = await this.$u.api.getTypesByCategory(categoryId)
      let data = JSON.parse(JSON.stringify(res))

      this.types = []
      data.forEach((item) => {
        let dat = {
          label: item.typeName,
          value: item.id,
          iconName: item.iconName
        }

        this.types.push(dat)
      })
    },
    /**
     * 账本选择编号赋值
     * @param {Object} e
     */
    changeBookClass(e) {
      this.account.accountBookId = e.value
      this.account.bookName = e.label
    },
    /**
     * 类型选择编号赋值
     * @param {Object} e
     */
    changeTypeClass(e) {
      this.account.accountCategoryId = e.value
      this.account.typeName = e.label
    },
    /**
     * 账本选择编号赋值 旧版
     * @param {Object} e
     */
    bookConfirm(e) {
      let index = e[0]
      let data = JSON.parse(JSON.stringify(this.books[index]))

      this.account.accountBookId = data.value
      this.account.bookName = data.label
      this.selBook[0] = index
    },
    /**
     * 类型选择编号赋值 旧版
     * @param {Object} e
     */
    typeConfirm(e) {
      let index = e[0]
      let data = JSON.parse(JSON.stringify(this.types[index]))

      this.account.accountCategoryId = data.value
      this.account.typeName = data.label
      this.selType[0] = index
    },
    /**
     * 记录时间赋值
     * @param {Object} e
     */
    timeConfirm(e) {
      let input = ''
      if (this.params.year) input += e.year
      if (this.params.month) input += '-' + e.month
      if (this.params.day) input += '-' + e.day
      if (this.params.hour) input += ' ' + e.hour
      if (this.params.minute) input += ':' + e.minute
      if (this.params.second) input += ':' + e.second

      this.account.createTime = input
    },
    // 按键被点击(点击退格键不会触发此事件)
    valChange(val) {
      if (this.account.amt.length > 10) return
      this.account.amt += val
    },
    // 退格键被点击
    backspace() {
      // 删除value的最后一个字符
      if (this.account.amt.length) {
        this.account.amt = this.account.amt.substr(0, this.account.amt.length - 1)
      }
    },
    /**
     * 更新
     */
    async update() {
      // 校验
      if (!this.account.name) {
        return
      }
      if (!this.account.accountCategoryId) {
        return
      }
      if (!this.account.amt) {
        return
      }
      if (!this.confirmIndex == 0) {
        return
      }

      // 设置不能再次点击 2秒后恢复
      this.confirmIndex += 1
      setTimeout(() => {
        this.confirmIndex = 0
      }, 2000)

      const res = await this.$u.api.upAccountRecord(this.account)

      if (res.data.isExceed) {
        // 超出预期
        this.$refs['Confirm'].open({
          title: '提示',
          content: `当前 [${this.account.typeName}] 支出类型月支出金额已超过预期，当前月总支出金额为 [${res.data.expenditureAmt}] 元~`,
          callback: (action) => {
            if (action == 'sumbit') {
              this.$u.toast('更新成功，正在为您跳转记录列表')

              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                  success: function () {
                    uni.$emit('refreshPage')
                  }
                })
              }, 1500)
            }
          }
        })
      } else {
        this.$u.toast('更新成功，正在为您跳转记录列表')

        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
            success: function () {
              uni.$emit('refreshPage')
            }
          })
        }, 1500)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 750rpx;
  color: #333333;

  .bg-top {
    margin-top: -1rpx;
    width: 750rpx;
    height: 220rpx;
    padding-top: 50rpx;
    border-radius: 0 0 20% 20%;

    .top-box {
      width: 700rpx;
      background-color: #ffffff;
      margin: 0 auto;
      border-radius: 20rpx;
      padding: 20rpx 30rpx 0rpx;
      position: relative;

      .qh-title {
        width: 100%;
        height: 60rpx;
        line-height: 65rpx;
      }
    }
  }

  .saveRecord {
    background-color: #dbf1e1;
    color: $u-tips-color;
    border: none;
    border-radius: 10px;
    font-size: 30rpx;

    &::after {
      border: none;
    }
  }
}

.category-subsection {
  width: 250rpx;
}

.input-width-220 {
  width: 220rpx;
}
</style>
